﻿$import( "SmitearWebGL.Objects.Canvas.ScreenQuad" );
$import( "SmitearWebGL.Programs.Hdr.DownSampleProgram" );

SmitearWebGL.Objects.Canvas.Hdr.DownSample = SmitearWebGL.Objects.Canvas.ScreenQuad.extend(
{
	/******** constructor ********/

	init : function()
	{
		this._super();
		this._registClass( "SmitearWebGL.Objects.Canvas.Hdr.DownSample" );

		this._downSampleTech = null;

		this._materials = null;
		this._offsets = null;
		this._usingSlot = -1;
	}
	,
	calculateOffsets : function()
	{
		var i, j, k, idx;
		var hdrTexture;
		var dsOffsetsX, dsOffsetsY;
		
		this._offsets = new Array( this._textures.length );
		for ( var k = 0; k < this._textures.length; ++ k )
		{
			hdrTexture =  this.getTextureAt(k);
	
			dsOffsetsX = new Float32Array( 16 );
			dsOffsetsY = new Float32Array( 16 );
			idx = 0;
			for( i = -2; i < 2; i++ )
			{
				for( j = -2; j < 2; j++ )
				{
					dsOffsetsX[idx] = ( i + 0.5 ) * ( 1.0 / hdrTexture.getWidth() );
					dsOffsetsY[idx] = ( j + 0.5 ) * ( 1.0 / hdrTexture.getHeight() );
					idx ++;
				}
			}
			this._offsets[k] = { offsetX : dsOffsetsX, offsetY : dsOffsetsY };
		}
	}
	,
	beforeRender : function()
	{
		var program = this._downSampleTech;
		
		var hr = SmitearWebGL.Core.HResult.SUCCESS;

		hr |= program.activeShader();
		
		hr |= this._vertexBuffer.bind();
		hr |= this._vertexBuffer.active( program.getShader() );
		
		return hr;
	}
	,
	//override render function
	renderCallBack : function( slot )
	{
		var program = this._downSampleTech;
		if ( ! program ) return SmitearWebGL.Core.HResult.UNKNOWN_TECHNIQUE;
		if ( ! program.getShader() ) return SmitearWebGL.Core.HResult.UNKNOWN_SHADER;
		
		var hr = SmitearWebGL.Core.HResult.SUCCESS;
		
		hr |= program.activeUniform( this._offsets[slot].offsetX, this._offsets[slot].offsetY, this.getTextureAt( slot ) );

		this.context.gl.drawArrays( this.context.gl.TRIANGLE_STRIP, 0, 4 );
		
		return hr;
	}
	,
	_createResource : function( params )
	{
		this._super();
		
		this._downSampleTech = this.context.programManager.getResourceByName( SmitearWebGL.Programs.InternalPrograms.Type.HDR_DOWN_SAMPLE );
	}
	,
	_destroyResource : function()
	{
		this._super();

		this._downSampleTech = null;

		this._materials = null;
		this._offsets = null;
		this._usingSlot = -1;
	}
}
);
